package com.application.moneycalculator.data;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;

import com.application.moneycalculator.activity.ListExpensesActivity;
import com.application.moneycalculator.db.MoneyCalculator;
import com.application.moneycalculator.log.Log_;
import com.application.moneycalculator.utils.DateUtils;

public class DBParser extends AsyncTask<ContentResolver, Integer, Integer> {
	
	private final String TAG = "DBParser";
	
	private static DBParser parser;
	
	private ListExpensesActivity listener;
	
	private ExpensesCollection collection;
	
	private boolean isDBLoaded = false;
	
	public enum ParserCode{
		PARSER_CODE_SUCESS,
		PARSER_CODE_FAILED
		;
	}

	public static DBParser getInstance()
	{
		if(parser == null)
		{
			parser = new DBParser();
		}
		return parser;
	}
	
	public void parse(ListExpensesActivity listener_)
	{
		if(listener_ != null)
		{
			this.listener = listener_;
		
			execute(listener.getContentResolver());
		}
		
	}

	@Override
	protected Integer doInBackground(ContentResolver... contentResolver) {
		Log_.out(TAG, "doInBackground");
		
		Cursor cursor = contentResolver[0].query(
					MoneyCalculator.Expense.CONTENT_URI, 
					new String []{MoneyCalculator.Expense._ID, MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_DATE, MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_AMOUNT, MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_CURRENCY}, 
					null, null, null);
		
		int count = 0;
		if(cursor != null && cursor.moveToFirst())
		{
			count = cursor.getCount();
		}
		
		Log_.out(TAG, "doInBackground, count from DB [" + count + "]");
		if(count > 0)
		{
			collection = new ExpensesCollection();
			
			int index = 0;		
			do {
				int indexDate = cursor.getColumnIndex(MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_DATE); 
				int indexAmount = cursor.getColumnIndex(MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_AMOUNT);
				int indexCurrency = cursor.getColumnIndex(MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_CURRENCY);
			    
	            // Get the field values
		        String valueDate = cursor.getString(indexDate);
		        int valueAmount = cursor.getInt(indexAmount);
		        int valueCurrency = cursor.getInt(indexCurrency);
		        
		        ExpenseItem expenseItem = DateUtils.convertStringToExpense(valueDate);
		        expenseItem.setAmountMoney(valueAmount);
		        expenseItem.setMoneyCurrency(valueCurrency);
		        
		        collection.addExpense(expenseItem);
		        
		        Log_.out(TAG, "doInBackground, idnex [" + index + "], date [" + valueDate + "], amount money [" + valueAmount + "], currency [" + valueCurrency + "]");
		        
				publishProgress((int) ((index / (float) count) * 100));
				
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				index++;
			} while (cursor.moveToNext());
		}

		return count;
	}
	
	protected void onPreExecute()
	{
		Log_.out(TAG, "onPreExecute");
		//show progress bar
	}
	
	protected void onProgressUpdate(Integer... progress) {
		Log_.out(TAG, "onProgressUpdate");
        //setProgressPercent(progress[0]);
		if(listener != null && listener.getProgressBar() != null)
		{
			Log_.out(TAG, "onProgressUpdate, try to update progress bar");
			listener.getProgressBar().setProgress(progress[0]);
		}
		else
		{
			Log_.out(TAG, "onProgressUpdate, listener or progressBar is null");
		}
    }
	
	protected void onPostExecute(ParserCode result) {
		Log_.out(TAG, "onPostExecute");
		//stop progress bar
		
		isDBLoaded = true;//result == ParserCode.PARSER_CODE_SUCESS ? true : false;
		
		if(this.listener != null)
		{
			listener.loaded(collection, ParserCode.PARSER_CODE_SUCESS);
		}
    }
	
	public boolean isDBLoaded()
	{
		return isDBLoaded;
	}

}
